package myThread;

import java.util.PriorityQueue;

class MyTask implements Comparable<MyTask>{
    private Runnable task;
    private long time;
    public MyTask(Runnable task , long time){
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
    public long getTime(){
        return time;
    }
    public void run(){
        task.run();
    }

}
class MyTimer{
    private PriorityQueue<MyTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public void schedule(Runnable task , long delay){
        synchronized (locker){
            MyTask myTask = new MyTask(task,System.currentTimeMillis()+delay);
            queue.offer(myTask);
            locker.notify();
        }
    }
    public MyTimer(){
        Thread t = new Thread(()->{
            try {
                while(true){
                    synchronized (locker){
                        while(queue.isEmpty()){
                           locker.wait();
                        }
                        MyTask task = queue.peek();
                        if(task.getTime()>System.currentTimeMillis()){
                            locker.wait(task.getTime()-System.currentTimeMillis());
                        }else {
                            task.run();
                            queue.poll();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }
}
public class demo37 {
}
